; docformat = 'rst'
;
;+
;
; :Purpose:
;   Estimate emissions, initial conditions, stratospheric lifetimes and/or OH concentrations
;
; :Inputs:
;   case_name: (required) String variable, name for the simulation
;   
; :Requires:
;   Root input and output path must be set in batch file a2i_path.pro
;
;   Required files:
;     {AIF_DIRECTORY}/{CASE_NAME}/emissions/{POLLUTANT_0}.csv,
;     {AIF_DIRECTORY}/{CASE_NAME}/emissions/{POLLUTANT_1}.csv, ...
;     {AIF_DIRECTORY}/{CASE_NAME}/parameters.csv
;     {AIF_DIRECTORY}/a2i_pollutant_parameters.csv
;
; :Keywords:
;   nProcesses: (Input, optional) number of processors to use.  
;     If greater than 1, sensitivity calculated on nProcessors.
;   it_start: (Input, optional) iteration to start on (if Monte-Carlo ensemble required)
;   it_end: (Input, optional) iteration to end on (if Monte-Carlo ensemble required)
;
; :Example::
;   a2i_run, 'CFC', nProcesses=6
;
; :History:
; 	Written by: Matt Rigby, MIT, Sep 6, 2012
;
;-
pro a2i_run, case_name, nProcesses=nProcesses, it_start=it_start, it_end=it_end, nIterations=nIterations, $
  alpha=alpha, mc=mc, linear=linear, emissions_no_modify=emissions_no_modify

  compile_opt idl2, hidden

  ;Check case name
  if n_elements(case_name) eq 0 then begin
    message, "AIF_RUN: CASE_NAME needed"
    return
  endif

  ;Set up threads
  print, strcompress('Running ' + case_name)
  if keyword_set(nProcesses) eq 0 then begin
    cpu, tpool_nthreads=!CPU.HW_NCPU
    nProcesses=1
  endif else begin
    cpu, tpool_nthreads=min([!CPU.HW_NCPU, nProcesses])
  endelse
  print, strcompress(string(nProcesses) + ' processes')
  print, strcompress(string(!CPU.TPOOL_NTHREADS) + ' threads')
  
  ;Retrieve parameters (parameters.csv and a2i_pollutant_parameters<_XXX>.csv files must be present)
  parameters=a2i_parameters(case_name)

  ;If perturbed simulations, set start and end iterations
  if keyword_set(it_start) eq 0 then it_start=0
  if keyword_set(it_end) eq 0 then it_end=0

  ;Check if linear, set to only one iteration
  if n_elements(linear) gt 0 then begin
    if linear eq 1 then begin
      alpha=1.d
      nIterations=1
    endif
  endif


  ;Run reference simulation 
  if it_start eq 0 then begin
    t0=systime(/seconds)
    a2i_invert, parameters, nProcesses=nProcesses, nIterations=nIterations, alpha=alpha, mc=mc, $
      linear=linear, emissions_no_modify=emissions_no_modify
    print, strcompress(string((systime(/seconds) - t0)/60.) + ' minutes')
  endif
  if it_start eq 0 then it_start++

  ;Run perturbed simulations, if required
  for it=it_start, it_end do begin
    t0=systime(/seconds)
    a2i_invert, parameters, emissions_bias=parameters['EMISSIONS_BIAS_ERROR'], iteration=it, $
      nProcesses=nProcesses, alpha=alpha, mc=mc, nIterations=nIterations, linear=linear, $
      emissions_no_modify=emissions_no_modify
    print, strcompress(string((systime(/seconds) - t0)/60.) + ' minutes')
  endfor

end